<template>
  <view class="order-list-container">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <input class="search-input" v-model="searchText" placeholder="输入商品或订单号搜索" />
      <view class="search-btn" @click="handleSearch">搜索</view>
    </view>
    <!-- 顶部tab -->
    <view class="order-tabs">
      <view v-for="(tab, idx) in tabs" :key="tab.value" :class="['order-tab', {active: currentTab === idx}]" @click="switchTab(idx)">
        {{ tab.label }}
      </view>
    </view>
    <!-- 订单列表 -->
    <view v-if="orderList.length > 0" class="order-list">
      <view class="order-item" v-for="order in orderList" :key="order.id">
        <view class="order-header">
          <view class="order-time">{{ order.createTime }}</view>
          <view class="order-status">{{ getOrderStatusName(order.orderStatus) }}</view>
        </view>
        <view class="order-products" v-if="order.orderItems && order.orderItems.length">
          <view class="order-product" v-for="item in order.orderItems" :key="item.id">
            <image :src="item.productImg" class="order-img" />
            <view class="product-info">
              <view class="product-title">{{ item.productName }}</view>
              <view class="product-meta">
                <text class="product-price">￥{{ item.salePrice }}</text>
                <text class="product-num">x{{ item.quantity }}</text>
              </view>
            </view>
          </view>
        </view>
        <view class="order-summary">
          共{{ order.orderItems ? order.orderItems.length : 0 }}件商品，总金额 <text class="order-amount">￥{{ order.payAmount || calcOrderTotal(order) }}</text>
        </view>
        <view class="order-actions">
          <button v-if="order.orderStatus === 0" class="order-btn pay">去支付</button>
          <button v-if="order.orderStatus === 1" class="order-btn">提醒发货</button>
          <button v-if="order.orderStatus === 2" class="order-btn">确认收货</button>
          <button v-if="order.orderStatus === 3" class="order-btn" @click="goToReview(order)">去评价</button>
          <button class="order-btn detail" @click="goOrderDetail(order.id)">查看详情</button>
        </view>
      </view>
    </view>
    <!-- 空状态 -->
    <view v-else class="empty-order">
      <image src="/static/images/empty-order.png" class="empty-img" mode="widthFix" />
      <view class="empty-text">暂无订单信息~</view>
    </view>
	</view>
</template>

<script>
import { getOrderList } from '@/api/order/order'
	export default {
		data() {
			return {
      searchText: '',
      currentTab: 0,
      tabs: [
        { label: '待付款', value: 0 },
        { label: '待发货', value: 1 },
        { label: '待收货', value: 2 },
        { label: '待评价', value: 3 },
        { label: '已完成', value: 4 }
      ],
      orderList: []
			}
		},
		methods: {
    switchTab(idx) {
      this.currentTab = idx
      this.loadOrders()
    },
    handleSearch() {
      this.loadOrders()
    },
    getOrderStatusName(status) {
      const map = {
        0: '待付款',
        1: '待发货',
        2: '待收货',
        3: '待评价',
        4: '已完成'
      }
      return map[status] || '未知状态'
    },
    calcOrderTotal(order) {
      if (!order.orderItems || !order.orderItems.length) return order.payAmount || '0.00'
      return order.orderItems.reduce((sum, item) => sum + (Number(item.salePrice) * Number(item.quantity)), 0).toFixed(2)
    },
    async loadOrders() {
      const status = this.tabs[this.currentTab].value
      try {
        const res = await getOrderList(status)
        console.log('API返回的原始数据:', res)
        
        // 处理返回的数据结构
        let orders = []
        if (res.data) {
          orders = Array.isArray(res.data) ? res.data : [res.data]
        } else if (res.rows) {
          orders = Array.isArray(res.rows) ? res.rows : [res.rows]
        } else if (Array.isArray(res)) {
          orders = res
        }
        
        console.log('提取的订单数组:', orders)
        
        // 兜底处理，保证每个订单的orderItems至少是空数组
        this.orderList = orders.map(order => {
          console.log('处理订单:', order)
          
          // 检查可能的商品信息字段名
          let orderItems = order.orderItems || order.items || order.products || []
          
          // 如果orderItems是字符串，尝试解析
          if (typeof orderItems === 'string') {
            try {
              orderItems = JSON.parse(orderItems)
            } catch (e) {
              console.error('解析orderItems失败:', e)
              orderItems = []
            }
          }
          
          return {
            ...order,
            orderItems: Array.isArray(orderItems) ? orderItems : []
          }
        })
        
        console.log('处理后的orderList:', this.orderList)
      } catch (e) {
        console.error('加载订单列表失败:', e)
        this.orderList = []
      }
    },
    goOrderDetail(orderId) {
      this.$tab.navigateTo(`/pages/order/detail?id=${orderId}`)
    },
    goToReview(order) {
      console.log('点击评价的订单信息:', order)
      
      // 检查订单基本信息
      if (!order || !order.id) {
        uni.showToast({
          title: '订单信息不完整',
          icon: 'none'
        })
        return
      }
      
      // 直接跳转到商品选择页面，传递订单ID
      this.$tab.navigateTo(`/pages/order/review-select?orderId=${order.id}`)
    }
  },
  onLoad(options) {
    if (options && options.status !== undefined) {
      const idx = this.tabs.findIndex(tab => tab.value == options.status)
      if (idx !== -1) {
        this.currentTab = idx
      }
    }
    this.loadOrders()
  },
  onShow() {
    // 页面显示时也刷新数据
    this.loadOrders()
  }
	}
</script>

<style lang="scss" scoped>
.order-list-container {
  min-height: 100vh;
  background: #fafbfc;
  padding-bottom: 30px;
}
.search-bar {
  display: flex;
  align-items: center;
  padding: 18px 16px 8px 16px;
  background: #fff;
  .search-input {
    flex: 1;
    height: 36px;
    border-radius: 18px;
    border: none;
    background: #f5f6f7;
    padding: 0 14px;
    font-size: 15px;
    outline: none;
  }
  .search-btn {
    margin-left: 10px;
    background: linear-gradient(90deg, #f54b4b 0%, #f87e36 100%);
    color: #fff;
    border-radius: 18px;
    padding: 0 18px;
    height: 36px;
    display: flex;
    align-items: center;
    font-size: 15px;
    cursor: pointer;
  }
}
.order-tabs {
  display: flex;
  background: #fff;
  padding: 0 0 8px 0;
  border-bottom: 1px solid #f0f0f0;
  .order-tab {
    flex: 1;
    text-align: center;
    font-size: 16px;
    color: #333;
    padding: 10px 0 6px 0;
    cursor: pointer;
    position: relative;
    &.active {
      color: #3c96f3;
      font-weight: bold;
      border-bottom: 2px solid #3c96f3;
    }
  }
}
.order-list {
  margin: 18px 12px 0 12px;
  .order-item {
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(60,150,243,0.04);
    padding: 14px 12px;
    margin-bottom: 16px;
    position: relative;
  }
  .order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 14px;
    color: #888;
    margin-bottom: 8px;
  }
  .order-status {
    color: #f87e36;
    font-weight: bold;
  }
  .order-products {
    border-bottom: 1px solid #f0f0f0;
    padding-bottom: 8px;
    margin-bottom: 8px;
  }
  .order-product {
    display: flex;
    align-items: center;
    margin-bottom: 6px;
  }
  .order-img {
    width: 50px;
    height: 50px;
    border-radius: 6px;
    margin-right: 10px;
    background: #f5f5f5;
  }
  .product-info {
    flex: 1;
  }
  .product-title {
    font-size: 15px;
    color: #222;
    margin-bottom: 2px;
  }
  .product-meta {
    font-size: 13px;
    color: #888;
    .product-price {
      color: #f54b4b;
      margin-right: 10px;
    }
    .product-num {
      color: #888;
    }
  }
  .order-summary {
    font-size: 13px;
    color: #888;
    margin-bottom: 8px;
    .order-amount {
      color: #f54b4b;
      font-weight: bold;
    }
  }
  .order-actions {
    display: flex;
    gap: 10px;
    .order-btn {
      background: linear-gradient(90deg, #f54b4b 0%, #f87e36 100%);
      color: #fff;
      border: none;
      border-radius: 16px;
      padding: 4px 14px;
      font-size: 13px;
      cursor: pointer;
    }
    .pay {
      background: linear-gradient(90deg, #3c96f3 0%, #3cf3b2 100%);
    }
    .detail {
      background: #fff;
      color: #f87e36;
      border: 1px solid #f87e36;
    }
  }

}
.empty-order {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-top: 80px;
  .empty-img {
    width: 180px;
    margin-bottom: 18px;
    opacity: 0.7;
  }
  .empty-text {
    color: #aaa;
    font-size: 16px;
  }
}
</style>
